import React, { useState } from "react";
import { Page, useNavigate } from "zmp-ui";
import { useRecoilState, useSetRecoilState } from "recoil";
import { useI18n } from "../i18n";
import { version } from "../utils/baseUrl";
import Navbar from "../components/navbar";
import { 
  authTokenState, 
  currentUserState, 
  loginPageState, 
  selectedCountryCodeState,
  logout
} from "../state";

const SettingsPage: React.FunctionComponent = () => {
  const { t, locale, setLocale } = useI18n();
  const navigate = useNavigate();
  const [showLanguageDialog, setShowLanguageDialog] = useState(false);
  
  // 状态管理
  const setAuthToken = useSetRecoilState(authTokenState);
  const setCurrentUser = useSetRecoilState(currentUserState);
  const setLoginPageState = useSetRecoilState(loginPageState);
  const setSelectedCountryCode = useSetRecoilState(selectedCountryCodeState);

  const languages = [
    { code: "zh", label: t("settings.simplifiedChinese") },
    { code: "vi", label: t("settings.vietnamese") }
  ];

  const currentLanguage = languages.find(lang => lang.code === locale)?.label || t("settings.simplifiedChinese");

  const handleLanguageSelect = (langCode: string) => {
    setLocale(langCode as any);
    setShowLanguageDialog(false);
  };

  const handleLogout = () => {
    if (confirm(t("settings.confirmLogout"))) {
      // 使用统一的登出函数清理所有数据
      logout();
      
      // 清理所有用户相关状态
      setAuthToken(null);
      setCurrentUser(null);
      
      // 重置登录页面状态到初始状态
      setLoginPageState({
        pageType: 1,
        loginType: 0,
        agree: false
      });
      
      // 重置国家代码选择到默认值
      setSelectedCountryCode('84');
      
      console.log("用户退出登录，状态已清理");
      
      // 跳转到登录页面
      navigate('/login', { replace: true });
    }
  };

  const handleUserAgreement = () => {
    // 跳转到用户协议页面
    console.log("打开用户协议");
  };

  const handlePrivacyPolicy = () => {
    // 跳转到隐私政策页面
    console.log("打开隐私政策");
  };

  const handleDeregisterAccount = () => {
    // 跳转到注销账号页面
    console.log("打开注销账号页面");
  };

  const SettingItem: React.FC<{
    title: string;
    value?: string;
    onClick: () => void;
    showArrow?: boolean;
  }> = ({ title, value, onClick, showArrow = true }) => (
    <div
      onClick={onClick}
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '16px 28px',
        backgroundColor: '#fff',
        cursor: 'pointer',
        transition: 'background-color 0.2s'
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.backgroundColor = '#f5f5f5';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.backgroundColor = '#fff';
      }}
    >
      <span style={{
        fontSize: 14,
        fontWeight: '500',
        color: '#333'
      }}>
        {title}
      </span>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        {value && (
          <span style={{
            fontSize: 14,
            fontWeight: '500',
            color: '#333',
            marginRight: 8
          }}>
            {value}
          </span>
        )}
        {showArrow && (
          <span style={{
            fontSize: 16,
            color: '#999'
          }}>
            ›
          </span>
        )}
      </div>
    </div>
  );

  return (
    <Page className="page" style={{ padding: 0, background: '#f5f5f7' }}>
      {/* 顶部导航栏 */}
      <Navbar title={t("settings.title")} />

      {/* 设置选项列表 */}
      <div style={{ marginTop: 14 }}>
        {/* 切换语言 */}
        <SettingItem
          title={t("settings.switchLanguage")}
          value={currentLanguage}
          onClick={() => setShowLanguageDialog(true)}
        />
        
        {/* 分隔线 */}
        <div style={{ height: 4, backgroundColor: '#f0f0f2' }} />
        
        {/* 版本 */}
        <SettingItem
          title={t("settings.version")}
          value={`V ${version}`}
          onClick={() => {}}
          showArrow={false}
        />
        
        {/* 分隔线 */}
        <div style={{ height: 4, backgroundColor: '#f0f0f2' }} />
        
        {/* 用户协议 */}
        <SettingItem
          title={t("settings.userAgreement")}
          onClick={handleUserAgreement}
        />
        
        {/* 分隔线 */}
        <div style={{ height: 4, backgroundColor: '#f0f0f2' }} />
        
        {/* 隐私政策 */}
        <SettingItem
          title={t("settings.privacyPolicy")}
          onClick={handlePrivacyPolicy}
        />
        
        {/* 分隔线 */}
        <div style={{ height: 4, backgroundColor: '#f0f0f2' }} />
        
        {/* 注销账号 */}
        {/* <SettingItem
          title={t("settings.deregisterAccount")}
          onClick={handleDeregisterAccount}
        /> */}
        
        {/* 分隔线 */}
        {/* <div style={{ height: 4, backgroundColor: '#f0f0f2' }} /> */}
      </div>

      {/* 退出登录按钮 */}
      <div style={{
        position: 'fixed',
        bottom: 14,
        left: 14,
        right: 14
      }}>
        <button
          onClick={handleLogout}
          style={{
            width: '100%',
            height: 52,
            backgroundColor: '#000',
            color: '#fff',
            border: 'none',
            borderRadius: 8,
            fontSize: 17,
            fontWeight: 'bold',
            cursor: 'pointer',
            transition: 'background-color 0.2s'
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.backgroundColor = '#333';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.backgroundColor = '#000';
          }}
        >
          {t("settings.logout")}
        </button>
      </div>

      {/* 语言选择对话框 */}
      {showLanguageDialog && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0,0,0,0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000
        }}>
          <div style={{
            backgroundColor: '#fff',
            borderRadius: 12,
            padding: 20,
            margin: 20,
            minWidth: 280,
            maxWidth: 400
          }}>
            <h3 style={{
              fontSize: 18,
              fontWeight: 'bold',
              color: '#333',
              margin: '0 0 20px 0',
              textAlign: 'center'
            }}>
              {t("settings.selectLanguage")}
            </h3>
            
            {languages.map((lang) => (
              <div
                key={lang.code}
                onClick={() => handleLanguageSelect(lang.code)}
                style={{
                  padding: '12px 16px',
                  cursor: 'pointer',
                  borderRadius: 8,
                  marginBottom: 8,
                  backgroundColor: locale === lang.code ? '#f0f0f0' : 'transparent',
                  transition: 'background-color 0.2s'
                }}
                onMouseEnter={(e) => {
                  if (locale !== lang.code) {
                    e.currentTarget.style.backgroundColor = '#f5f5f5';
                  }
                }}
                onMouseLeave={(e) => {
                  if (locale !== lang.code) {
                    e.currentTarget.style.backgroundColor = 'transparent';
                  }
                }}
              >
                <span style={{
                  fontSize: 16,
                  color: '#333'
                }}>
                  {lang.label}
                </span>
                {locale === lang.code && (
                  <span style={{
                    float: 'right',
                    color: '#007AFF',
                    fontSize: 16
                  }}>
                    ✓
                  </span>
                )}
              </div>
            ))}
            
            <div style={{
              display: 'flex',
              justifyContent: 'center',
              marginTop: 20
            }}>
              <button
                onClick={() => setShowLanguageDialog(false)}
                style={{
                  padding: '8px 24px',
                  backgroundColor: '#f0f0f0',
                  color: '#333',
                  border: 'none',
                  borderRadius: 6,
                  fontSize: 14,
                  cursor: 'pointer'
                }}
              >
                取消
              </button>
            </div>
          </div>
        </div>
      )}
    </Page>
  );
};

export default SettingsPage;
